package com.mairuide.inspectionReport;

import com.alibaba.fastjson.JSONObject;
import com.mairuide._frame.base.BaseRepository;
import com.mairuide._frame.base.BaseServiceProxy;
import com.mairuide._frame.utils.Config;
import com.mairuide._frame.utils.Testtrans;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.DealFlowService;
import com.mairuide.datalog.DataOperationImportLog;
import com.mairuide.entity.PageResult;
import com.mairuide.inspectionReport.utils.MeiYaJsoupUtils;
import com.mairuide.inspectionReport.utils.RuiHaiJsoupUtils;
import com.mairuide.phone.PhoneRecord;
import com.mairuide.phone.import_phone.PhoneRecordingService;
import org.hibernate.SQLQuery;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Auther: zyj
 * @Date: 2019/3/20 11:24
 * @Description:
 */

@Service
@Transactional(readOnly = true)
public class ReportService extends BaseServiceProxy<Report> {

    @Autowired
    private ReportDao reportDao;
    @Autowired
    private MailListDao mailListDao;
    @Autowired
    private PhoneRecordingService phoneRecordingService;
    @Autowired
    private DealFlowService dealFlowService;
    @PersistenceContext
    private EntityManager entityManager;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    protected Config config;

    @Override
    protected BaseRepository<Report> getBaseRepository() {
        return reportDao;
    }

    public PageResult findByCasemanageId(String caseId,Integer page,Integer size){
        String sql = "select * from TB_DATA_OPERATION_IMPORT_LOG where CASEMANAGE_ID = '"+caseId+"' and TABLE_FLAT = 3 ";
        long count = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM ("+sql+" ) t", long.class);
        Query query = this.entityManager.createNativeQuery(sql);
        // 将查询结果集转为Map
        query.unwrap(SQLQuery.class).setResultTransformer(new Testtrans(DataOperationImportLog.class));
        // 设置分页
        query.setFirstResult((page - 1) * size);
        query.setMaxResults(size);
        // 获取查询结果集
        List<DealFlow> list = query.getResultList();
        PageResult pageResult = new PageResult(count, list);
        return pageResult;
    }

    /**
     * 美亚手机取证信息抓取
     *
     * @param fileName
     * @param caseId
     * @param id
     * @throws IOException
     */
    public void extractionMeiYa(String fileName,String caseId,Integer id) throws IOException {
        String zipPath =config.getUploadFilePath()+"\\report\\"+fileName+"\\Report\\Catalog.html";
        File in = new File(zipPath);
        Document document = Jsoup.parse(in, "UTF-8");
        /*取得script下面的JS变量*/
        Elements e = document.getElementsByTag("script").eq(2);
        Map<String, String> map = null;
        for (Element element:e){
            /*取得JS变量数组*/
            String[] data = element.data().split("var");
            /*取得单个JS变量*/
            for(String variable : data){
                /*取到满足条件的JS变量*/
                if(variable.startsWith(" zNodes")){
                    variable =variable.substring(9,variable.lastIndexOf(";"));
                    List<ZNodes> list = JSONObject.parseArray(variable,ZNodes.class);
                    for (ZNodes node:list) {
                        if (Pattern.matches("银行\\(\\d+\\)",node.getName())){//银行信息
//                            MeiYaJsoupUtils.cyberBank(config.getUploadFilePath()+"\\report\\"+fileName+"\\Report\\",node.getUrl());

                        }else if (Pattern.matches("转账\\(\\d+\\)",node.getName())){//微信
                            List<DealFlow> dealList = MeiYaJsoupUtils.weiXin(config.getUploadFilePath()+"\\report\\"+fileName+"\\Report\\",node.getUrl(),caseId,id);
                            dealFlowService.save(dealList);
                        }else if (Pattern.matches("好友资金往来\\(\\d+\\)",node.getName())){//支付宝
                            List<DealFlow> dealList = MeiYaJsoupUtils.aliplay(config.getUploadFilePath()+"\\report\\"+fileName+"\\Report\\",node.getUrl(),caseId,id);
                            dealFlowService.save(dealList);
                        }else if (Pattern.matches("手机\\(\\d+\\)",node.getName())){//通讯录
                            List<MailList> phone = MeiYaJsoupUtils.phone(config.getUploadFilePath() + "\\report\\" + fileName + "\\Report\\", node.getUrl(), caseId, map);
                            mailListDao.save(phone);
                        }else if (Pattern.matches("全部通话记录\\(\\d+\\)",node.getName())){//通话记录
                            List<PhoneRecord> phone = MeiYaJsoupUtils.callRecord(config.getUploadFilePath() + "\\report\\" + fileName + "\\Report\\", node.getUrl(), caseId, map);
                            phoneRecordingService.save(phone);
                        }else if (Pattern.matches("基本信息\\(\\d+\\)",node.getName())){//基本信息
                            map = MeiYaJsoupUtils.basicInfo(config.getUploadFilePath() + "\\report\\" + fileName + "\\Report\\", node.getUrl());
                        }
                    }
                }
            }
        }
    }

    public void extractionRuiHai(String fileName,String caseId,Integer id) throws IOException {
        String zipPath =config.getUploadFilePath()+"\\report\\"+fileName+"\\瑞海_Report\\Menu.html";
        File in = new File(zipPath);
        Document document = Jsoup.parse(in, "UTF-8");
        zipPath = zipPath.substring(0,zipPath.lastIndexOf("\\")+1);
        /*取得script下面的JS变量*/
        Element element = document.getElementsByTag("script").eq(3).get(0);
        String[] split = element.data().substring(0,element.data().length()-19).split(";d\\.add");
        for (int i=1;i<split.length;i++){
            String[] strings = split[i].split(",");
            String url = strings[2].replace("'","").trim();
            if (Pattern.matches("未删除通讯录\\(\\d+\\)",url)){
                RuiHaiJsoupUtils.phone(zipPath,strings[3].trim().replace("'",""),0,caseId);
            }else if (Pattern.matches("已删除通讯录\\(\\d+\\)",url)){
                RuiHaiJsoupUtils.phone(zipPath,strings[3].trim().replace("'",""),1,caseId);
            }else if (Pattern.matches("接听\\(\\d+\\)",url)){
                String pid = strings[0].substring(1);
                while (true){
                    i++;
                    String[] jietign = split[i].split(",");
                    if (!pid.equals(jietign[1].trim())){
                        i--;
                        break;
                    }
                    RuiHaiJsoupUtils.callRecord(zipPath,jietign[3].trim().replace("'",""),1,caseId);
                }
            }else if (Pattern.matches("拨打\\(\\d+\\)",url)){
                String pid = strings[0].substring(1);
                while (true){
                    i++;
                    String[] jietign = split[i].split(",");
                    if (!pid.equals(jietign[1].trim())){
                        i--;
                        break;
                    }
                    RuiHaiJsoupUtils.callRecord(zipPath,jietign[3].trim().replace("'",""),0,caseId);
                }
            }
        }
    }

}
